package org.wupuser.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupuser.model.User;

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
	@Query(value = "select u from User u where u.isDeleted = false ")
	List<User> findAll();
	
	@Query(value = "select u from User u where u.username like CONCAT('%',:username,'%') and u.isDeleted = false ")
	List<User> findByUsernameLike(@Param("username") String username);
	
	@Query(value = "select u from User u where u.username = :username and u.isDeleted = false ")
	User findByUsername(@Param("username") String username);
	
	@Query(value = "select u from User u where u.id = :id and u.isDeleted = false ")
	User findUserById(@Param("id") Long id);
	
	@Query(value = "select u from User u where u.email = :email and u.isDeleted = false ")
	User findByEmail(@Param("email") String email);
	
	@Transactional
	@Modifying
	@Query(value = "insert into User (username, password, email, createTime, updateTime, isDeleted) values( :#{#user.username}, :#{#user.password}, :#{#user.email}, :#{#user.createTime}, :#{#user.updateTime}, :#{#user.isDeleted})")
	void saveUser(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(value = "update User u set u.updateTime = :#{#user.updateTime}, u.password = :#{#user.password} where u.id = :#{#user.id}")
	void updatePassword(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(value = "update User u set u.updateTime = :#{#user.updateTime}, u.email = :#{#user.email} where u.id = :#{#user.id}")
	void updateEmail(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(value = "update User u set u.updateTime = :#{#user.updateTime},u.signatrue = :#{#user.signatrue} where u.id = :#{#user.id}")
	void updateInfo(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(value = "update User u set u.updateTime = :#{#user.updateTime},u.avatar = :#{#user.avatar} where u.id = :#{#user.id}")
	void updateAvatar(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(value = "update User u set u.updateTime = :#{#user.updateTime},u.username = :#{#user.username} where u.id = :#{#user.id}")
	void updateUsername(User user);
	
	@Transactional
	@Modifying
	@Query(value = "update User u set u.updateTime = :#{#user.updateTime},u.isDeleted = false where u.id = :#{#user.id}")
	void deleteUser(@Param("user") User user);
}
